package com.zhengjiang.purchase.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author zhengjiang
 * @version 1.0.0
 * @description redis 配置
 * @date 2021/6/20
 **/
@Configuration
public class RedisConfig {

    private RedisConnectionFactory connectionFactory = null;

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private String maxIdle;
    @Value("${spring.redis.jedis.pool.max-active}")
    private String maxTotal;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private String maxWait;

    @Bean(name = "redisConnectionFactory")
    public RedisConnectionFactory initRedisConnectionFactory(){
        if (connectionFactory!=null){
            return this.connectionFactory;
        }
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(Integer.valueOf(maxIdle));
        poolConfig.setMaxTotal(Integer.valueOf(maxTotal));
        poolConfig.setMaxWaitMillis(Long.valueOf(maxWait));
        //创建jedis连接工厂
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory(poolConfig);
        connectionFactory.setHostName(host);
        connectionFactory.setPort(Integer.valueOf(port));
        connectionFactory.setPassword(password);
        this.connectionFactory = connectionFactory;
        return connectionFactory;
    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<Object,Object> initRedisTemplate(){
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(initRedisConnectionFactory());
        return redisTemplate;
    }
}
